package com.google.gwt.mobile.phonegap.resources;

import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.HeadElement;
import com.google.gwt.dom.client.ScriptElement;

/**
 * The Class JavaScriptInjector.
 */
public class JavaScriptInjector {

  private static HeadElement head;

  /**
   * Inject in head.
   * 
   * @param javascript the javascript
   */
  public static void injectInHead(String javascript) {
    HeadElement head = getHead();
    ScriptElement element = createScriptElement();
    element.setText(javascript);
    head.appendChild(element);
  }

  /**
   * Inject in body.
   * 
   * @param javascript the javascript
   */
  public static void injectInBody(String javascript) {
    ScriptElement element = createScriptElement();
    element.setText(javascript);
    Document.get().getBody().appendChild(element);
  }

  private static ScriptElement createScriptElement() {
    ScriptElement script = Document.get().createScriptElement();
    script.setType("text/javascript");
    return script;
  }

  private static HeadElement getHead() {
    if (head == null) {
      Element headElement = Document.get().getElementsByTagName("head").getItem(0);

      if (headElement != null) {
        HeadElement head = HeadElement.as(headElement);
        JavaScriptInjector.head = head;
      }
    }
    return JavaScriptInjector.head;
  }
}
